<template>
  <!-- 项目管理：文档内容 -->
  <div style="width:100%;background:#E9E9E9;">
    <div class="mainPart" :class="device==='mobile'?'mobileMainPart':''">
      <div class="mainItem menuPart">
        <el-button id="menuBtn" size="mini" type="primary" @click="handleMenu">目录管理</el-button>
        <el-tree ref="structureTree" :data="structureList" empty-text="暂无数据"
          node-key="id" :props="defaultProps" @node-click="chooseStructure"></el-tree>
      </div>
      <div class="mainItem mainContent">
        <div class="oper">
          <p style="text-align:left;font-size:15px;font-weight:bolder;line-height:20px;margin:6px 0;" v-show="currentCate">当前目录：{{ currentCate }}</p>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini"
                :disabled="cateId && !hasFile?false:true" @click="addText('add')">新增文本</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini"
                :disabled="cateId && !hasFile?false:true" @click="addPicture('add')">新增图片</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini"
                :disabled="cateId && !hasFile?false:true" @click="addTable('add')">新增表格</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini"
                :disabled="cateId && !hasFile?false:true" @click="addFile('add')">新增附件</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-sort" size="mini"
                :disabled="cateId && !hasFile?false:true" @click="changeSort">变更排序</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-finished" size="mini"
                @click="startSaveSort" v-show="sortPartVisible">保存排序</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button plain icon="el-icon-close" size="mini"
                @click="cancelChangeSort" v-show="sortPartVisible">取消排序</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="cardBox" v-for="(vo, index) in currentContentList" :key="index" :style="{'margin-top':index==0&&sortPartVisible?'8px':'0'}" v-show="currentContentList.length">
          <div :id="'sortPart_'+vo.contId" class="sortPart" v-show="sortPartVisible">
            <input type="number" :id="'sortNum_'+vo.sortNum" class="sortInput" v-model="vo.sortNum" />
          </div>
          <div class="cardContent" :style="{'text-align':vo.contType=='2'?'center':'left'}">
            <p v-show="vo.contType=='1'" v-html="vo.content"></p>
            <div v-show="vo.contType=='2' || vo.contType=='4'">
              <el-image :src="vo.content.url">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
              <p class="captionPart" v-html="vo.content.caption"></p>
            </div>
            <div v-show="vo.contType=='3'">
              <el-table 
                v-if="vo.tableData && vo.columnData"
                :show-header="false" border
                size="small"
                :data="vo.tableData"
              >
                <el-table-column
                    v-for="(col, index) in vo.columnData"
                    :key="`column_list_${col.prop || col.slotIdentify}_${index}`"
                    v-bind="col"
                >
                  <template slot-scope="{ row }">
                    <span>{{ col.formatter ? col.formatter(row, column) : row[col.prop] }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <p class="captionPart">题注：{{ vo.caption || "" }}</p>
            </div>
            <div v-show="vo.contType=='5'">见运行手册：
              <p class="contentFileName" @click="previewFile(vo.content)">{{ vo.content.name }}</p>
            </div>
          </div>
          <!-- <div class="signPart">
            <el-button type="text" icon="el-icon-edit" size="mini"
              @click="editContent(vo)" v-show="vo.contType=='1'">编辑</el-button>
            <el-button type="text" plain icon="el-icon-edit" size="mini"
              @click="changePic(vo)" v-show="vo.contType=='2'">更换</el-button>
            <el-button type="text" icon="el-icon-delete" size="mini"
              @click="deleteContent(vo.contId, vo.contType)">删除</el-button>
          </div> -->
          <div class="signPart">
            <el-dropdown style="width:100%;">
              <span class="el-dropdown-link" style="color:#1890ff;">
                <i class="el-icon-more el-icon--right" style="transform:rotate(90deg);"></i>操作
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-show="vo.contType=='1'">
                  <div @click="editContent(vo)"><i class="el-icon-edit"></i> 编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-show="vo.contType=='2'">
                  <div @click="changePic(vo)"><i class="el-icon-edit"></i> 更换</div>
                </el-dropdown-item>
                <el-dropdown-item v-show="vo.contType=='3'">
                  <div @click="editTableContent(vo)"><i class="el-icon-edit"></i> 编辑</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="deleteContent(vo.contId, vo.contType)"><i class="el-icon-delete"></i> 删除</div>
                </el-dropdown-item>
                <el-dropdown-item v-show="index < currentContentList.length-1 && vo.contType!='5'">
                  <div @click="startInsert(vo)"><i class="el-icon-bottom-right"></i> 插入下一行</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-tooltip class="tipPart" effect="dark" :content="'当前'+vo.editingBy+'正在编辑'" placement="right" v-if="vo.isEditing">
              <el-button><i class="el-icon-edit"></i></el-button>
            </el-tooltip>
          </div>
        </div>
        <div id="noData" v-show="!currentContentList.length">暂无内容</div>
      </div>
    </div>
        
    <!-- 内容目录-start -->
    <el-dialog title="内容目录" :visible.sync="menuVisible" :width="device==='mobile'?'100%':'900px'">
      <content-menu ref="menuPart" @getStructureList="getStructureList" @closeMenuPage="closeMenuPage"></content-menu>
    </el-dialog>
    <!-- 内容目录-end -->
    <!-- 新增|编辑文本-start -->
    <el-dialog :title="(contId?'编辑':'新增')+'文本'" :append-to-body="true" :close-on-click-modal="false" :before-close="beforeCloseSet"
               :visible.sync="textVisible" :width="device==='mobile'?'90%':'762px'">
      <el-form ref="contentForm" :model="contentForm" :rules="textRules">
        <el-form-item label="字号">
          <el-input-number v-model="currentFontSize" @change="fontSizeChange" :min="14" :max="24" size="small"></el-input-number>
        </el-form-item>
        <el-form-item prop="content">
          <el-input type="textarea" rows="16" v-model="contentForm.content" resize="none" maxlength="1000" show-word-limit
                    :autosize="{minRows:18, maxRows:26}" :style="{'font-size':currentFontSize+'px'}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeTextPage('quit')">取 消</el-button>
        <el-button type="primary" @click="saveInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增|编辑文本-end -->
    <!-- 新增|变更图片-start -->
    <el-dialog :title="(contId?'变更':'新增')+'图片'" :append-to-body="true" :close-on-click-modal="false" :before-close="beforeCloseSet"
               :visible.sync="pictureVisible" :width="device==='mobile'?'90%':'762px'">
      <el-form ref="pictureForm" :model="pictureForm" :rules="pictureRules" :inline="true">
        <el-form-item label="图片" prop="url">
          <el-upload
            ref="pictureUpload"
            class="upload-demo"
            :action="uploadFileUrl"
            :headers='headers'
            :multiple="false"
            :show-file-list="true"
            list-type="picture"
            :limit="1"
            :auto-upload="true"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess">
            <el-button type="primary" plain icon="el-icon-upload" size="mini"
              :disabled="cateId?false:true">{{ contId?"变更":"新增"}}图片</el-button>
          </el-upload>
        </el-form-item><br />
        <el-form-item label="题注" prop="caption">
          <el-input v-model="pictureForm.caption" style="width:300px;" />
        </el-form-item>
        <el-form-item label="当前图片" v-if="pictureForm.url && contId">
          <img :src="pictureForm.url" style="max-width:554px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePicturePage('quit')">取 消</el-button>
        <el-button type="primary" @click="saveUploadFile">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增|变更图片-end -->
    <!-- 新增|编辑表格-start -->
    <el-dialog :title="(contId?'编辑':'插入')+'表格'" :append-to-body="true" :close-on-click-modal="false" :before-close="beforeCloseSet"
               :visible.sync="tableVisible" :destroy-on-close="true" width="92%" style="max-width: 1600px; margin: 0 auto;">
      <table-editor ref="tableEditorRef"></table-editor>
      <el-form ref="tableForm" :model="tableForm" :rules="tableRules" label-width="50px" style="width: 100%;">
        <el-form-item label="题注" prop="caption" style="margin: 0;">
          <el-input v-model="tableForm.caption" size="small"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeTablePage('quit')">取 消</el-button>
        <el-button type="primary" @click="saveTableInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增|编辑表格-end -->
    <!-- 新增附件-start -->
    <el-dialog title="新增附件" :append-to-body="true" :close-on-click-modal="false" :visible.sync="fileVisible" :width="device==='mobile'?'90%':'800px'">
      <file-add ref="fileAddPart"></file-add>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFilePage">取 消</el-button>
        <el-button type="primary" @click="saveInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增附件-end -->
    <!-- 插入项选择--start -->
    <el-dialog title="提示" :append-to-body="true" :close-on-click-modal="false" :visible.sync="insertVisible" :destroy-on-close="true" :width="device==='mobile'?'90%':'420px'">
      <div>您要往下一行插入什么内容?</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="insertContent('1')">插入文本</el-button>
        <el-button type="primary" size="mini" @click="insertContent('2')">插入图片</el-button>
        <el-button type="primary" size="mini" @click="insertContent('3')">插入表格</el-button>
      </div>
    </el-dialog>
    <!-- 插入项选择--end -->
  </div>
</template>

<script>
  import { Loading } from 'element-ui';
  import { getToken } from "@/utils/auth";
  import { mapGetters } from 'vuex';
  import html2canvas from 'html2canvas';
  import leafletImage from 'leaflet-image';
  import { listContMenu } from "@/api/project/contentMenu";
  import ContentMenu from '@/views/project/ContentMenu';
  import { formatData, formatContent, resetContentVal } from '@/api/common/common';
  import { listContentInfo, contentInfoSave, detailContentInfo, deleteContentInfo, setSort, setIsEditing, cancelIsEditing } from "@/api/project/contentInfo";
  import { saveFile, deleteFileByFileUrl } from "@/api/upload/upload";
  import TableEditor from '@/views/project/common/TableEditor.vue';
  import FileAdd from '@/views/project/common/FileAdd.vue';
  import request from '@/utils/request'

  export default {
    name: 'ProjectContent',
    components:{ ContentMenu, TableEditor, FileAdd },
    data(){
      return {
        projectId:this.$route.query.projectId,
        structureList:[],
        defaultProps:{
          label: 'cateName',
          children: 'children'
        },
        cateId:"",
        currentCate:"",
        currentContentList:[],  // 当前节点处的内容
        currentType:"", // 当前编辑状态：新增编辑add|插入insert
        textVisible:false,
        contId:"",  // 当前选中文本块
        currentFontSize:16, // 当前文本字号
        contentForm:{
          contType:"1",
          content:"",
          sortNum:1,
        },
        textRules:{
          content:[{required: true, message: '请输入文本内容', trigger: 'blur'}]
        },
        pictureVisible:false,
        originalPictureInfo:{},
        pictureUploadInfo:{},
        pictureForm:{
          url:"", // 图片地址
          caption:"", // 图片题注
        },
        pictureRules:{
          url:[{required: true, message: '请选择图片', trigger: 'change'}],
          caption:[{required: true, message: '请输入题注', trigger: 'blur'}]
        },
        uploadFileUrl:process.env.VUE_APP_BASE_API + '/common/upload',
        headers:{Authorization:"Bearer " + getToken()},
        fileId:"",  // 当前已上传的文件id
        sortPartVisible:false, // 排序区域显示
        originalContentList:[], // 原有排序的文本内容
        // 模板目录
        menuVisible:false,

        // 表格相关
        tableVisible: false,
        tableForm: {
          caption: ""
        },
        tableRules: {
          caption: [{required: true, message: '请输入题注', trigger: 'blur'}]
        },

        // 附件
        fileVisible:false,
        hasFile:false,  // 是否含有附件
        
        // 插入下一行
        insertVisible:false,
        insertInfo:{},

        // websocket
        wsObj:null,
        wsUrl:""
      }
    },
    computed: {
      ...mapGetters([
        'nickName', 'name', 'device'
      ])
    },
    created(){
      this.getStructureList();

      this.wsUrl = process.env.VUE_APP_WEBSOCKET_URL+"/ws/editing/"+this.projectId+"/"+this.name;
      this.initWebsocket();
    },
    activated(){
      this.projectId = this.$route.query.projectId;
    },
    watch:{
      projectId(){
        this.getStructureList();
        this.cateId = "";
        this.currentCate = "";
        this.currentContentList = [];
      }
    },
    methods:{
      // websocket初始化
      initWebsocket(){
        this.wsObj = new WebSocket(this.wsUrl);

        this.wsObj.onopen = ()=>{}

        this.wsObj.onerror = ()=>{
          this.wsObj = new WebSocket(this.wsUrl);
        }

        this.wsObj.onclose = ()=>{
          this.wsObj = new WebSocket(this.wsUrl);
        }

        this.wsObj.onmessage = (e)=>{
          let data = JSON.parse(e.data);
          console.log("data", data);
          this.$notify({
            title: '成功',
            message: data.msg,
            type: 'success'
          });
          detailContentInfo(data.contId).then(ret=>{
            if(ret.code == 200){
              if(this.currentContentList.length){
                this.currentContentList.map((vo, index)=>{
                  if(vo.contId == data.contId){
                    if(vo.contType!="1") ret.data.content = JSON.parse(ret.data.content);
                    ret.data.tableData = ret.data.content.table;
                    ret.data.columnData = ret.data.content.column;
                    ret.data.caption = ret.data.content.caption;
                    this.$set(this.currentContentList, index, ret.data);
                  }
                })
              }
            }else{}
          })
        }
      },

      // 获取文档结构
      getStructureList(){
        listContMenu({
          projectId:this.projectId
        }).then(ret=>{
          this.structureList = formatData(ret.rows, 0);
        }).catch();
      },

      // 选择结构
      chooseStructure(obj, node, treeComponent){
        if(!obj.children.length){
          console.log(obj);
          console.log(node);
          this.cateId = obj.cateId;
          this.currentCate = obj.cateName;
          this.getContentInfo();
        }
      },

      // 获取文档内容
      getContentInfo(){
        let loadingInstance = Loading.service({ fullscreen: true, background:"rgba(0,0,0,0.5)" });
        this.hasFile = false;
        listContentInfo({
          projectId:this.projectId,
          cateId:this.cateId
        }).then(ret=>{
          if(ret.code == 200){
            this.currentContentList = [];
            ret.rows.map((vo, index)=>{
              if(vo.contType=="2" || vo.contType=='4'){
                vo.content = JSON.parse(vo.content);
              }else if (vo.contType=='3') {
                const content = JSON.parse(vo.content)
                vo.caption = content.caption;
                vo.tableData = content.table;
                vo.columnData = content.column;
              }else if(vo.contType=='5'){
                vo.content = JSON.parse(vo.content);
                this.hasFile = true;
              }
              this.currentContentList.push(vo);
            })
          }else{
            this.$message.error(ret.msg);
          }
          loadingInstance.close();
        })
        .catch(err=>{
          console.log(err);
          loadingInstance.close();
        })
      },

      // 设置编辑状态
      setIsEditing(contId){
        setIsEditing({
          contId:contId
        }).then(ret=>{
          console.log("ret", ret)
          if(ret.code == 200){}else{}
        })
      },

      // 取消设置编辑状态
      cancelIsEditing(contId){
        cancelIsEditing({
          contId:contId
        }).then(ret=>{}).catch(err=>{})
      },

      // 模板内容目录
      handleMenu(){
        this.menuVisible = true;
        this.$nextTick(()=>{
          this.$refs.menuPart.chosenParentMenu = "";
          this.$refs.menuPart.chosenMenu = "";
          this.$refs.menuPart.$refs.menuForm.resetFields();
          this.$refs.menuPart.getMenuList(this.projectId);
        })
      },

      // 新增文本
      addText(type, info){
        this.currentType = type;
        this.textVisible = true;
        this.contId = "";
        this.contentForm.content = "";
        this.$nextTick(()=>{
          this.contentForm.contType = "1";
          if(this.contentForm.contId) delete this.contentForm.contId;
          this.$refs.contentForm.resetFields();
          if(type == "add"){
            // 新增
            if(this.currentContentList.length){
              this.contentForm.sortNum = Number(this.currentContentList[this.currentContentList.length-1].sortNum)+1;
            }else{
              this.contentForm.sortNum = Number(this.currentContentList.length) + 1;
            }
          }else{
            // 插入 @params type insert
            this.contentForm.sortNum = Number(info.sortNum) + 1;
          }
        })
      },

      // 字号变化监听
      fontSizeChange(currentVal, oldVal){
        // console.log(currentVal, oldVal);
        // console.log(this.currentFontSize);
      },

      // 编辑文本
      editContent(info){
        detailContentInfo(info.contId).then(res=>{
          if(res.code == 200){
            if(!res.data.isEditing){
              this.currentType = "add";
              this.cateId = info.cateId;
              this.contId = info.contId;
              this.contentForm.contType = info.contType;
              this.setIsEditing(info.contId);
              if(info.contType == 1){
                this.contentForm.content = resetContentVal(info.content);
              }else{
                this.contentForm.content = info.content;
              }
              this.contentForm.sortNum = info.sortNum;
              this.textVisible = true;
            }else{
              this.$message.warning("当前有人正在编辑，请稍后");
            }
          }else{}
        }).catch();
      },

      // 新增图片
      addPicture(type, info){
        this.currentType = type;
        this.contId = "";
        if(this.contentForm.contId) delete this.contentForm.contId;
        this.contentForm.contType = "2";
        this.contentForm.content = "";
        if(type == "add"){
          // 新增
          if(this.currentContentList.length){
            this.contentForm.sortNum = Number(this.currentContentList[this.currentContentList.length-1].sortNum)+1;
          }else{
            this.contentForm.sortNum = Number(this.currentContentList.length) + 1;
          }
        }else{
          // 插入 @params type insert
          this.contentForm.sortNum = Number(info.sortNum) + 1;
        }
        this.pictureVisible = true;
        this.$nextTick(()=>{
          this.$refs.pictureForm.resetFields();
        })
      },

      // 更换图片
      changePic(info){
        console.log(info);
        detailContentInfo(info.contId).then(res=>{
          if(res.code == 200){
            if(!res.data.isEditing){
              this.contId = info.contId;
              this.setIsEditing(info.contId);
              this.pictureVisible = true;
              this.pictureForm.caption = resetContentVal(info.content.caption);
              this.pictureForm.url = info.content.url;
              this.originalPictureInfo = {
                url:info.content.url,
                sortNum:info.sortNum
              };
            }else{
              this.$message.warning("当前有人正在编辑，请稍后");
            }
          }else{}
        }).catch();
      },

      // 图片上传前
      beforeUpload(file){
        console.log("beforeUpload");
      },

      // 上传成功
      uploadSuccess(res, file){
        if(res.code == 200){
          this.$message.success("上传成功");
          this.pictureForm.url = res.url;
          this.pictureUploadInfo = res;
          this.pictureUploadInfo.fileSize = file.size;
        }else{
          this.$message.error(ret.msg);
        }
      },

      // 保存已上传的文件
      saveUploadFile(){
        this.$refs.pictureForm.validate((valid) => {
          if(valid){
            this.contentForm.content = JSON.stringify({
              url:this.pictureForm.url,
              caption:formatContent(this.pictureForm.caption)
            });
            this.contentForm.contType = "2";
            if(this.contId && this.originalPictureInfo.url==this.pictureForm.url){
              this.saveContent();
            }else{
              saveFile({
                objId:this.cateId,
                objType: 1,
                fileName: this.pictureUploadInfo.originalFilename,
                fileSize: this.pictureUploadInfo.fileSize,
                fileSuffix: this.pictureUploadInfo.newFileName.split(".")[1],
                fileURL:this.pictureUploadInfo.url
              }).then(ret=>{
                if(ret.code == 200){
                  this.fileId = ret.data;
                  this.saveContent();
                }else{}
              }).catch()
            }
          }
        })
      },

      // 新增附件
      addFile(type, info){
        // 若要添加附件，则该章节不能有其他内容
        if(this.currentContentList.length){
          this.$message.warning("当前章节已有内容，不可新增附件！");
          return false;
        }
        this.currentType = "add";
        this.contId = "";
        if(this.contentForm.contId) delete this.contentForm.contId;
        this.contentForm.contType = "5";
        this.contentForm.content = "";
        this.contentForm.sortNum = 1;
        this.fileVisible = true;
        this.$nextTick(()=>{
          this.$refs.fileAddPart.currentFileInfo = {};
          this.$refs.fileAddPart.getDocumentList();
        })
      },

      // 预览附件
      previewFile(file){
        window.open(file.url, '_blank');
      },

      // 插入下一行
      startInsert(info){
        this.insertInfo = info;
        this.insertVisible = true;
      },
      insertContent(type){
        this.insertVisible = false;
        switch (type) {
          case "1":
            // 插入文本
            this.addText('insert', this.insertInfo);
            break;
          case "2":
            // 插入图片
            this.addPicture('insert', this.insertInfo);
            break;
          case "3":
            // 插入表格
            this.addTable('insert', this.insertInfo);
            break;
        }
      },

      // 删除信息
      deleteContent(contId, contType){
        detailContentInfo(contId).then(res=>{
          if(res.code == 200){
            if(!res.data.isEditing){
              this.$confirm("您确定要删除该"+(contType=="2"?"图片":"文本信息")+"？！", "提示", {
                confirmButtonText:"删除",
                cancelButtonText:"取消",
                type:"warning"
              }).then(()=>{
                this.setIsEditing(contId);
                deleteContentInfo(contId).then(ret=>{
                  if(ret.code == 200){
                    this.$message.success("删除成功！");
                    this.getContentInfo();
                  }else{
                    this.$message.error(ret.msg);
                  }
                }).catch(err=>{
                  console.log(err);
                })
              }).catch(()=>{
                this.cancelIsEditing(contId);
              })
            }else{
              this.$message.warning("当前有人正在编辑，请稍后");
            }
          }else{}
        }).catch();
      },

      // 保存
      saveInfo() {
        if(this.contentForm.contType == "1"){
          // 文本
          this.$refs.contentForm.validate((valid) => {
            if(valid){
              this.saveContent();
            }else{
              return false;
            }
          });
        }else if(this.contentForm.contType == "5"){
          // 附件
          if(!this.$refs.fileAddPart.currentFileInfo.fileId){
            this.$message.warning("您还未选择文档");
            return false;
          }
          let obj = {
            url:this.$refs.fileAddPart.currentFileInfo.fileURL,
            name:this.$refs.fileAddPart.currentFileInfo.fileName
          }
          this.$set(this.contentForm, "content", JSON.stringify(obj));
          this.saveContent();
        }else{
          this.saveContent();
        }
      },
      saveContent(){
        let loadingInstance = Loading.service({ fullscreen: true, background:"rgba(0,0,0,0.5)" });
        let params = this.contentForm;
        params.projectId = this.projectId;
        params.cateId = this.cateId;
        if(this.contentForm.contType == "1"){
          // 文本
          params.content = formatContent(this.contentForm.content);
        }else if(this.contentForm.contType == "5"){
          // 附件
          params.sortNum = 1;
          let obj = {
            url:this.$refs.fileAddPart.currentFileInfo.fileURL,
            name:this.$refs.fileAddPart.currentFileInfo.fileName
          }
          params.content = JSON.stringify(obj);
        }
        if(this.contId){
          params.contId = this.contId;
          if(this.contentForm.contType=="2") params.sortNum = this.originalPictureInfo.sortNum;
        }else{
          if(this.contentForm.contType=="2" || this.contentForm.contentType=="4"){
            params.docUploadFile = {
              fileId:this.fileId
            };
          }
        }
        console.log("params",params)

        contentInfoSave(params).then(ret=>{
          loadingInstance.close();
          if(ret.code == 200){
            this.$message.success("保存成功！");
            if(this.currentType == "insert") this.setSort("insert");
            this.contentForm.content = "";
            if(this.contentForm.contType == "1"){
              // 文档
              this.$refs.contentForm.resetFields();
              this.closeTextPage();
            }else if(this.contentForm.contType == "2"){
              // 图片
              if(this.contId && this.originalPictureInfo.url!=this.pictureForm.url){
                deleteFileByFileUrl({
                  fileUrl:this.originalPictureInfo.url
                }).then(ret=>{
                  if(ret.code == 200){
                    this.$message.success("原图片已删除");
                  }else{}
                }).catch()
              }
              this.$refs.pictureForm.resetFields();
              this.$refs.pictureUpload.clearFiles();
              this.closePicturePage();
            }else if(this.contentForm.contType == "5"){
              // 附件
              this.$refs.fileAddPart.currentFileInfo = {};
              this.closeFilePage();
            }
            setTimeout(() => {
              this.getContentInfo();
            }, 10);
          }else{
            this.$message.error(ret.msg);
          }
        }).catch(err=>{
          console.log(err);
          loadingInstance.close();
        })
      },

      beforeCloseSet(done){
        if(this.contId) this.cancelIsEditing(this.contId);
        setTimeout(() => {
          done();
        }, 100);
      },

      // 关闭
      closeTextPage(type){
        if(this.contId && type=="quit") this.cancelIsEditing(this.contId);
        this.contentForm.contType = "1";
        this.contentForm.content = "";
        this.contentForm.sortNum = 1;
        this.textVisible = false;
      },
      closePicturePage(type){
        if(this.contId && type=="quit") this.cancelIsEditing(this.contId);
        this.contId = "";
        this.contentForm.content = "";
        this.contentForm.contType = "2";
        this.contentForm.sortNum = 1;
        this.pictureVisible = false;
      },
      closeFilePage(){
        if(this.contId) this.cancelIsEditing(this.contId);
        this.contId = "";
        this.contentForm.content = "";
        this.contentForm.contType = "5";
        this.contentForm.sortNum = 1;
        this.fileVisible = false;
      },
      closeMenuPage(){
        this.menuVisible = false;
      },

      // 变更排序
      changeSort(){
        this.sortPartVisible = true;
        this.originalContentList = JSON.parse(JSON.stringify(this.currentContentList));
      },
      startSaveSort(){
        this.$confirm("您确定要保存当前已更改的排序？！", "提示", {
          confirmButtonText:"保存",
          cancelButtonText:"取消",
          type:"warning"
        }).then(()=>{
          this.setSort("");
        }).catch()
      },
      setSort(type){
        console.log("type", type);
        this.currentType = type;
        let contIdArr = document.getElementsByClassName("sortPart");
        let sortNumArr = document.getElementsByClassName("sortInput");
        let sortArr = [];
        for(let i = 0; i < contIdArr.length; i++){
          if(!sortNumArr[i].id.split("_")[1]){
            this.$message.warning("您还有部分内容的排序未填写！");
            return false;
          }
          if(type == "insert" && sortNumArr[i].id.split("_")[1] >= this.contentForm.sortNum){
            // 插入时更新段落排序
            sortArr.push({
              contId:contIdArr[i].id.split("_")[1],
              sortNum:Number(sortNumArr[i].id.split("_")[1])+1
            })
          }else{
            sortArr.push({
              contId:contIdArr[i].id.split("_")[1],
              sortNum:sortNumArr[i].id.split("_")[1]
            })
          }
          if(i == contIdArr.length-1){
            setSort(sortArr).then(ret=>{
              if(ret.code == 200){
                this.$message.success("排序已更新");
                this.sortPartVisible = false;
                this.getContentInfo();
              }else{
                this.$message.error(ret.msg);
              }
            }).catch(err=>{})
          }
        }
      },

      // 取消排序
      cancelChangeSort(){
        this.sortPartVisible = false;
        this.currentContentList = JSON.parse(JSON.stringify(this.originalContentList));
        console.log(this.originalContentList)
        console.log(this.currentContentList);
      },

      /* 表格插入 */
      addTable(type, info) {
        this.currentType = type;
        this.tableForm.caption = "";
        this.tableVisible = true;
        this.contId = "";
        this.contentForm.contType = "3";
        this.contentForm.content  = "";
        if(this.contentForm.contId) delete this.contentForm.contId;
        if(type == "add"){
          // 新增
          if(this.currentContentList.length){
            this.contentForm.sortNum = Number(this.currentContentList[this.currentContentList.length-1].sortNum)+1;
          }else{
            this.contentForm.sortNum = Number(this.currentContentList.length) + 1;
          }
        }else{
          // 插入 @params type insert
          this.contentForm.sortNum = Number(info.sortNum) + 1;
        }
      },
      saveTableInfo() {
        const columnData = this.$refs.tableEditorRef.columnData;
        if (!columnData.length) {
          this.$message.warning("表格列不能为空！")
          return
        }
        const tableData = this.$refs.tableEditorRef.tableData;
        if (!tableData.length) {
          this.$message.warning("表格不能为空！")
          return
        }
        this.$refs.tableForm.validate((valid) => {
          if(valid){
            this.saveTableContent(columnData, tableData);
          }else{
            return false;
          }
        });
      },
      saveTableContent(columnData, tableData) {
        let loadingInstance = Loading.service({ fullscreen: true, background:"rgba(0,0,0,0.5)" });
        let params = this.contentForm;
        params.projectId = this.projectId;
        params.cateId = this.cateId;
        params.content = JSON.stringify({
          table: tableData,
          column: columnData.filter(v => v.prop),
          caption: this.tableForm.caption
        });
        if(this.contId){
          params.contId = this.contId;
        }else{
          params.sortNum = this.contentForm.sortNum;
        }

        contentInfoSave(params).then(ret=>{
          loadingInstance.close();
          if(ret.code == 200){
            this.$message.success("保存成功！");
            if(this.currentType == "insert") this.setSort("insert");
            this.closeTablePage();
            setTimeout(() => {
              this.getContentInfo();
            }, 10);
          }else{
            this.$message.error(ret.msg);
          }
        }).catch(err=>{
          console.log(err);
          loadingInstance.close();
        })
      },
      editTableContent(vo) {
        detailContentInfo(vo.contId).then(res=>{
          if(res.code == 200){
            if(!res.data.isEditing){
              this.cateId = vo.cateId;
              this.contId = vo.contId;
              this.setIsEditing(vo.contId);
              this.contentForm.contType = vo.contType;
              this.contentForm.sortNum = vo.sortNum;
              this.tableVisible = true;
              this.$nextTick(() => {
                this.tableForm.caption = vo.caption
                this.$refs.tableEditorRef.formInline = {
                  row: vo.tableData.length,
                  col: vo.columnData.length
                }
                this.$refs.tableEditorRef.genTimes = 1
                this.$refs.tableEditorRef.columnData = [
                  ...vo.columnData,
                  {
                    label: "操作",
                    slotIdentify: "operation",
                    align: "center",
                    width: 80,
                    fixed: "right"
                  }
                ]
                this.$refs.tableEditorRef.tableData = vo.tableData
                this.$refs.tableEditorRef.tshow = false
                this.$refs.tableEditorRef.$nextTick(() => {
                    this.$refs.tableEditorRef.tshow = true
                })
              })
            }else{
              this.$message.warning("当前有人正在编辑，请稍后");
            }
          }else{}
        }).catch();
      },
      closeTablePage(type) {
        if(this.contId && type=="quit") this.cancelIsEditing(this.contId);
        this.contentForm.contType = "1";
        this.contentForm.content = "";
        this.contentForm.sortNum = 1;
        this.tableVisible = false;
      }
    },
    destroyed(){
      if(this.wsObj){
        this.wsObj.close();
        this.wsObj = null;
      }
    }
  }
</script>

<style scoped>
  .oper{
    top: 10px;
    position: absolute;
  }
  .mainPart{
    width:1140px;
    /*height:100%;*/
    min-height:calc(100vh - 84px);
    font-size:14px;
    margin:0 auto;
    box-sizing:border-box;
    padding: 10px 0;
    position:relative;
  }
  .mainPart .mainItem{
    height:100%;
    min-height:500px;
    background-color:#FFF;
    padding:8px;
    overflow-y:auto;
    position:relative;
    box-sizing:border-box;
  }
  .mainPart .mainItem.menuPart{
    height:calc(100vh - 104px);
    /*width:300px;*/
    width:336px;
    margin-right:10px;
    position:fixed;
  }
  .el-tree >>> .el-tree-node{
    padding:4px 0;
    white-space:normal;
  }
  .mainPart .mainItem.mainContent{
    /*width:calc(100% - 310px);*/
    width: 794px;
    overflow-x: hidden;
    padding:96px 118px;
    margin-left:346px;
    position:relative;
    /*border:1px solid #C6C6C6;*/
  }
  .mainPart >>> .el-tree-node.is-current:not(.is-expanded) .el-tree-node__content{
    color: #1890ff!important;
    background: #e8f4ff!important;
  }
  #menuBtn{
    position:absolute;
    top:5px;
    right:5px;
    z-index:1;
  }
  .cardBox{
    width:100%;
    color: #303133;
    border:1px solid #FFF;
    position:relative;
  }
  .cardBox:hover{
    border:1px solid #FAFAFA;
    border-radius:6px;
    /*background-color:#FAFAFA;*/
    background-color:#FFFFE7;
  }
  .cardBox .sortPart{
    width:65px;
    height:28px;
    line-height:28px;
    border:1px solid #CCC;
    position:absolute;
    left:-70px;
  }
  .cardBox .sortPart >>> .el-input__inner{
    width:100%;
    height:100%;
    font-size:16px;
    font-weight:bolder;
    padding: 0 5px;
    text-align: center;
    border: none;
  }
  .cardBox .sortInput{
    width: 100%;
    height:25px;
    text-align: center;
    border: none;
  }
  .cardBox input.sortInput:focus-visible{
    outline: none;
  }
  /* .cardBox .cardContent{
    width:calc(100% - 60px);
    padding-right:6px;
  } */
  .cardBox .cardContent >>> span{
    display:inline-block;
    margin:0;
    text-indent:32px;
  }
  .cardBox .signPart{
    width:96px;
    min-height:30px;
    border-left:2px solid #F56C6C;
    position:absolute;
    top:0;
    right:-100px;
  }
  .cardBox .signPart .el-button{
    font-size:12px;
    margin:0 3px;
    border: none;
  }
  .cardBox .signPart .el-button:hover{
    color: #F56C6C;
    border: none;
    /*color: #FFF;*/
    /*background-color: #1890ff;*/
  }
  .el-dropdown-menu >>> .el-dropdown-menu__item{
    width:100%!important;
    padding:0!important;
  }
  .el-dropdown-menu >>> .el-dropdown-menu__item div{
    width:100%;
    padding:0 17px;
  }
  .cardBox p{
    font-size:16px;
    text-indent: 32px;
    line-height:28px;
    margin:0;
  }
  .cardBox .el-image{
    object-fit:cover;
  }
  .mainPart p.captionPart{
    font-size:12px;
    color:#8B8585;
    text-align:center;
    text-indent:0;
  }
  /* 附件名称 */
  p.contentFileName{
    color:#1890ff;
    text-decoration:underline;
    text-indent:0;
    cursor:pointer;
    word-break:break-word;
  }
  #noData{
    width:100px;
    height:24px;
    line-height:24px;
    text-align:center;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
  }
  .el-textarea{
    margin-bottom:8px;
  }
  /* 批注 */
  .tipPart{
    text-align:center;
    padding:5px;
    background-color:rgba(242, 199, 199, 0.5);
    color:red;
    border-radius:100%;
    position:absolute;
    top:0;
    right:0;
    z-index:999;
  }

  /* 手机端 */
  .mobileMainPart{
    width:100%;
    overflow:hidden;
  }
  .mainPart.mobileMainPart .oper .el-row{
    width: calc(100% + 90px);
    margin-left: -50px!important;
  }
  .mainPart.mobileMainPart .oper .el-row .el-col{
    margin-bottom:5px;
  }
  .mainPart.mobileMainPart .mainItem.menuPart{
    width:100%;
    min-height:150px;
    max-height:200px;
    height:200px;
    position:relative;
  }
  .mainPart.mobileMainPart .mainItem.mainContent{
    width:100%;
    height:calc(100% - 200px);
    margin:15px 0 0;
  }
  .mainPart.mobileMainPart .mainItem.mainContent{
    padding:102px 106px 96px 84px;
  }
</style>